//
//  StatusCell.swift
//  SinaWeibo
//
//  Created by NeXTSTEP on 15/10/1.
//  Copyright © 2015年 NeXTSTEP. All rights reserved.
//

import UIKit
import SDWebImage

let WBStatusCellSelectPictureNotification = "StatusCellSelectPictureNotification"
let WBStatusCellSelectPictureURLKey = "StatusCellSelectPictureURLKey"
let WBStatusCellSelectPictureIndexKey = "StatusCellSelectPictureIndexKey"


class StatusCell: UITableViewCell {
    @IBOutlet weak var headImage: UIImageView!
    @IBOutlet weak var name: UILabel!
    @IBOutlet weak var time: UILabel!
    @IBOutlet weak var source: UILabel!
    @IBOutlet weak var contentLabel: UILabel!
    @IBOutlet weak var pictureViewWidth: NSLayoutConstraint!
    
    @IBOutlet weak var pictureViewHeight: NSLayoutConstraint!
    
    @IBOutlet weak var pictureViewLayout: UICollectionViewFlowLayout!
    
    
    @IBOutlet weak var pictureView: UICollectionView!
    
    @IBOutlet weak var BottomView: UIView!
    
    var status: Status? {
        didSet {
            headImage.sd_setImageWithURL(status?.user?.imageURL)
            name.text = status?.user?.name
            source.text = status?.source
            time.text = status?.created_at
            contentLabel.text = status?.text
            // 计算配图大小
            let pSize = calcPictureViewSize(status!)
            pictureViewWidth.constant = pSize.viewSize.width
            pictureViewHeight.constant = pSize.viewSize.height
            // 设置 layout 的大小
            pictureViewLayout.itemSize = pSize.itemSize
            
            pictureView.reloadData()
        }
    }
    

    /**
    计算图像视图的大小
    
    1> 没有图像，CGRectZero
    2> 一张图片，图像的原始尺寸
    3> 4张图片，固定大小的 2 * 2
    4> 多张图片，固定大小的 3 * 3
    
    元组->可以包含多个值
    */
    private func calcPictureViewSize(status: Status) -> (viewSize: CGSize, itemSize: CGSize) {
        
        // 单张图片默认大小
        let s: CGFloat = 90
        let itemSize = CGSizeMake(s, s)
        // 图片间距
        let m: CGFloat = 10
        // 图片的数量
        let imageCount = status.pictureURLS?.count ?? 0
        
        // 1. 没有图像
        if imageCount == 0 {
            return (CGSizeZero, itemSize)
        }
        
        // 2. 一张图片
        if imageCount == 1 {
            // 利用 sdwebimage 从缓存加载图像
            // 缓存图像的 key 是 图像的 URL，注意：不是保存在磁盘中的图片名
            // 保存的文件名，是 URL 的 MD5
            let key = status.pictureURLS![0].absoluteString
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            
            //            println("单张图片 \(image.size)")
            return (image.size, image.size)
        }
        
        // 3. 四张图片
        if imageCount == 4 {
            //            println("四张图片")
            return (CGSizeMake(s * 2 + m, s * 2 + m), itemSize)
        }
        
        // 4. 执行到此，就是多张图片
        // 1> 计算行数
        /**
        1, 2, 3 => 1
        4, 5, 6 => 2
        */
        //        println("多张图片 \(imageCount)")
        let row = CGFloat((imageCount - 1) / 3 + 1)
        return (CGSizeMake(s * 3 + m * 2, row * s + (row - 1) * m), itemSize)
    }
    
    
    func rowHeight(status: Status) -> CGFloat {
        self.status = status
        self.layoutIfNeeded()
        
        return CGRectGetMaxY(BottomView.frame)
    }
    
    override func awakeFromNib() {
        contentLabel.preferredMaxLayoutWidth = UIScreen.mainScreen().bounds.width - 16
    }

    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

    }

}

extension StatusCell : UICollectionViewDataSource,UICollectionViewDelegate {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return status?.pictureURLS?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell  = collectionView.dequeueReusableCellWithReuseIdentifier("PictureCell", forIndexPath: indexPath) as! PictureCell
        cell.url = status!.pictureURLS![indexPath.item]
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        //测试代码
//        let v = UIView()
//        let rect = cellFullFrameInScreen(indexPath)
//        v.frame = rect
//        v.backgroundColor = UIColor.redColor()
//        UIApplication.sharedApplication().keyWindow!.addSubview(v)
        
        
        NSNotificationCenter.defaultCenter().postNotificationName(WBStatusCellSelectPictureNotification, object: self, userInfo: [WBStatusCellSelectPictureURLKey: status!.largePictureURLs!,WBStatusCellSelectPictureIndexKey: indexPath])
        
    }
    
    func cellFrameInSrceen(indexPath: NSIndexPath) -> CGRect {
        let cell = pictureView.cellForItemAtIndexPath(indexPath)!
        return pictureView.convertRect(cell.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
    }
    
    func cellFullFrameInScreen(indexPath: NSIndexPath) -> CGRect {
        let key = status!.pictureURLS![indexPath.item].absoluteString
        let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
        
        let scale = image.size.height / image.size.width
        let screenSize = UIScreen.mainScreen().bounds.size
        let height = screenSize.width * scale
        
        //考虑长短图
        var y: CGFloat = 0
        if height < screenSize.height {
             y = (screenSize.height - height) * 0.5
        }
        return CGRect(x: 0, y: y, width: screenSize.width, height: height)
    }
    
}


class PictureCell : UICollectionViewCell {
    
    @IBOutlet weak var iconView: UIImageView!
    var url: NSURL? {
        didSet {
            iconView.sd_setImageWithURL(url!)
        }
    }
    
}
